//
//  HOTMineDetailListViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-15.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTOrenoListViewController.h"
#import "HOTOrenoListCell.h"
#import "HOTImagePriviewer.h"
#import "HOTCreateArticleViewController.h"
#import "HOTOrenoDetailViewController.h"

#define tab_1_cell_id @"tableView_1"
#define tab_2_cell_id
#define tab_3_cell_id

@interface HOTOrenoListViewController () <HOTOrenoListCellDelegate>{
    
    NSMutableDictionary *_cellCache;
//    NSMutableArray *_dataList1;
//    NSMutableArray *_dataList2;
//    NSMutableArray *_dataList3;
    
    NSInteger _pageNo;
}
@property(nonatomic,strong)NSMutableArray *dataList;
@property(nonatomic,copy)NSString *category_id;
@end

@implementation HOTOrenoListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil category_id:(NSString *)category_id
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.category_id = category_id;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_oreno"]];
    [self setNaviTitle:@"俺のシリーズ"];
    
    [self addRightBtnTarget:self action:@selector(createNewNoteBtnClicked:) image:[UIImage imageNamed:@"btn_note_off"] hImage:[UIImage imageNamed:@"btn_note_on"]];
    
    _tabAllBtn.selected = YES;
    
    _cellCache = [[NSMutableDictionary alloc] initWithCapacity:10];
    
#if 0
    NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"che@2x" withExtension:@"png"];
    NSURL *url2 = [[NSBundle mainBundle] URLForResource:@"che2@2x" withExtension:@"png"];
    NSArray *tempList = @[@{@"title":@"天井工事",@"imageUrl":url1,@"content":@"ジャーん！\n俺の愛車！！シーマLOVEな人いる？？"},
                          @{@"title":@"電気工事",@"imageUrl":[NSNull null],@"content":@"うひょー！やっばり面えがカッコよし！俺も欲かしい！！"},
                          @{@"title":@"電気工事",@"imageUrl":url2,@"content":@"うひょー！やっばり面えがカッコよし！俺も欲かしい！！"}];
    
    _dataList1 = [NSMutableArray arrayWithArray:tempList];
    
#endif
    
    _tableView.showHeader = YES;
    //_tableView.showFooter = YES;
    
    __unsafe_unretained HOTOrenoListViewController *tempObj = self;
    
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
        [tempObj requestDataFromNet];
    };
    
//    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
//        
//        _pageNo ++;
//        [tempObj requestDataFromNet];
//    };
    
    self.dataList = [NSMutableArray array];
    
    _pageNo = 1;
    //[self requestDataFromNet];
    
    _orenoSubList1ViewController = [[HOTOrenoSubListViewController alloc] initWithNibName:@"HOTOrenoSubListViewController" bundle:nil category_id:self.category_id reqType:@"0"];
    _orenoSubList1ViewController.parentNavc = self.navigationController;
    tableFrame = CGRectMake(0, 44, 320, 480);
    _orenoSubList1ViewController.view.frame = tableFrame;
    
    [self.view addSubview:_orenoSubList1ViewController.view];
}

-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_CATE_ID:[HOTUtils getString:self.category_id],
                                 REQ_KEY_TYPE:@"0",
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};
    
    __unsafe_unretained HOTOrenoListViewController *tempObj = self;
    [self requestWithURL:HOT_URL_USER_CONTENT Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];

        //[tempObj.dataList removeAllObjects];

        tempObj.dataList = [NSMutableArray arrayWithArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = tab_1_cell_id;
    HOTOrenoListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        cell = [_cellCache objectForKey:@(indexPath.row)];
        
        if (cell == nil) {
            
            cell = [self createTableCellWithCellId:cellId];
        }
    }
    
    cell.delegate = self;
    cell.indexPath = indexPath;
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    
    [self setCell:cell dic:dic];
    cell.majiLabel = [dic objectForKey:@"user_id"];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HOTOrenoListCell *cell = [tableView dequeueReusableCellWithIdentifier:tab_1_cell_id];
    
    if (cell == nil) {
        
        cell = [self createTableCellWithCellId:tab_1_cell_id];
        
        [_cellCache setObject:cell forKey:@(indexPath.row)];
    }
    
    
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    
    [self setCell:cell dic:dic];
    
    [cell setNeedsDisplay];
    [cell setNeedsUpdateConstraints];
    [cell.contentView setNeedsDisplay];
    [cell.contentView setNeedsUpdateConstraints];

    float cellH = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    
//    NSLog(@"cellH = %f",cellH);
    return cellH +1;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createNewNoteBtnClicked:(id)sender {
    
    HOTCreateArticleViewController *cavc = [[HOTCreateArticleViewController alloc] initWithNibName:@"HOTCreateArticleViewController" bundle:nil category_id:self.category_id];
    
    [self.navigationController pushViewController:cavc animated:YES];
}

-(void)setCell:(HOTOrenoListCell *)cell dic:(NSDictionary *)dic {
    
    cell.majiLabel.text = [NSString stringWithFormat:@"%@:",[dic objectForKey:@"user_name"]];
    //cell.titleLabel.text = [dic objectForKey:@"user_name"];
    cell.dateTimeLabel.text = [dic objectForKey:@"article_time"];
    cell.contentLabel.text = [dic objectForKey:@"article_content"];
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"pic_thumb_url"]];
    if (![url isKindOfClass:[NSNull class]]) {
        [cell setContentImage:url];
    } else {
        
        [cell setContentImage:nil];
    }
}

-(HOTOrenoListCell *)createTableCellWithCellId:(NSString *)cellId {

    UINib *nib = [UINib nibWithNibName:XIB(@"HOTOrenoListCell") bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:cellId];
        
    HOTOrenoListCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellId];
    
    return cell;
}

-(void)contentImageClicked:(NSIndexPath *)clickIndexPath {
    
    NSDictionary *dic = [self.dataList objectAtIndex:clickIndexPath.row];
    
    NSString *urlStr = [dic objectForKey:@"pic_url"];
    
    if ([HOTUtils isNotNullOrEmpty:urlStr]) {
        
        [[HOTImagePriviewer priviewer] showInView:[[UIApplication sharedApplication] keyWindow] withUrl:urlStr placeHolder:kImageHolder];
    } else {
        
    }
}

- (IBAction)tabAllBtnClicked:(id)sender {
    
    _tabOtherBtn.selected = NO;
    _tabSelfBtn.selected = NO;
    
    _tabAllBtn.selected = YES;

    [self.view bringSubviewToFront:_orenoSubList1ViewController.view];
}


- (IBAction)tabOtherBtnClicked:(id)sender {
    
    _tabAllBtn.selected = NO;
    _tabSelfBtn.selected = NO;
    
    _tabOtherBtn.selected = YES;
    
    if (_orenoSubList2ViewController == nil) {
        _orenoSubList2ViewController = [[HOTOrenoSubListViewController alloc] initWithNibName:@"HOTOrenoSubListViewController" bundle:nil category_id:self.category_id reqType:@"1"];
        _orenoSubList2ViewController.parentNavc = self.navigationController;
        _orenoSubList2ViewController.view.frame = tableFrame;
        
        [self.view addSubview:_orenoSubList2ViewController.view];
    }
    
    [self.view bringSubviewToFront:_orenoSubList2ViewController.view];
}
- (IBAction)tabSelfBtnClicked:(id)sender {
    
    _tabOtherBtn.selected = NO;
    _tabAllBtn.selected = NO;
    
    _tabSelfBtn.selected = YES;
    
    if (_orenoSubList3ViewController == nil) {
        _orenoSubList3ViewController = [[HOTOrenoSubListViewController alloc] initWithNibName:@"HOTOrenoSubListViewController" bundle:nil category_id:self.category_id reqType:@"2"];
        _orenoSubList3ViewController.parentNavc = self.navigationController;
        _orenoSubList3ViewController.view.frame = tableFrame;
        
        [self.view addSubview:_orenoSubList3ViewController.view];
    }
    
    [self.view bringSubviewToFront:_orenoSubList3ViewController.view];
}


@end
